<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;

class UserController extends BaseController
{

    /**
     * 邮箱+密码 登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(){
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
            $user = Auth::user();
            $data = $user->toArray();
            $data = array_merge($data,$this->_createToken($user));
            return $this->sendResponse($data, '登陆成功!');
        } else {
            return $this->sendError('登陆失败!');
        }
    }

    /**
     * 邮箱+密码+重复密码 注册
     *
     * @param UserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), User::RULES);

        if ($validator->fails()) {
            return $this->sendError($validator->errors());
        }

        $input = $request->all();
        //将密码进行加密
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);

        $data = $user->toArray();
        $data['name'] = $user->name;
        $data['email'] =  $user->email;
        $data['email_verified_at']= $user->email_verified_at;
        $data = array_merge($data,$this->_createToken($user));

        return $this->sendResponse($data, '注册成功!');
    }

    /**
     * Logout user (Revoke the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return $this->sendResponse(null, '退出成功!');
    }

    /**
     * 用户信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request) {
        $user = $request->user();

        $data = $user->toArray();
        if(isset($request->valid_days) && $request->valid_days < 5)//若用户的有效期不足5天，则刷新token，这个需要app 配合存新的token
            $data = array_merge($data,$this->_createToken($user));
        return $this->sendResponse($data, '获取用户信息成功!');
    }

    /**
     * 修改我的信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $user = $request->user();
        //$user = User::find(5);
        $message = $user->store($user->id,$request);
        if($message['success']){
            return $this->sendResponse($message['data'], $message['message']);
        }else{
            return $this->sendError($message['message']);
        }
    }

    /**
     * 获取上传token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadToken(Request $request,$disk)
    {
        $config = config("filesystems.disks.{$disk}");
        if(empty($config)){
            return response()->json(['success' => false, 'message' => '驱动不存在!'], 401);
        }else{
            $storage = Storage::disk($disk);
        }
        $data = [];
        switch ($disk){
            case 'qiniu' :
                $bucket=$config['bucket'];//上传空间名称
                $data['token'] = $storage->uploadToken();
                $data['url'] = $config['url'];
                $data['region'] = $config['region'];
                break;
            default:
                break;
        }

        return $this->sendResponse($data, '获取成功!');
    }

    /**
     * 创建accessToken
     *
     * @return array
     */
    protected function _createToken($user){
        $app = strstr(request()->userAgent(), ')', true).')';
        $tokenResult = $user->createToken($app);
        $data['token_type'] =  'Bearer';
        $data['access_token'] =  $tokenResult->accessToken;
        $data['expires_at'] = Carbon::parse($tokenResult->token->expires_at)->toDateTimeString();
        return $data;
    }
}
